using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users.Departments;

namespace Team.API.Applocation.Handler.Users.Departments
{
    /// <summary>
    /// 查询部门处理器
    /// </summary>
    public class QueryDepartmentHandler : IRequestHandler<QueryDepartmentCommand, APIPaging<DepartmentDTO>>
    {
        private readonly IRepository<Departmentmodel> departmentRepository;

        public QueryDepartmentHandler(IRepository<Departmentmodel> departmentRepository)
        {
            this.departmentRepository = departmentRepository;
        }

        public async Task<APIPaging<DepartmentDTO>> Handle(QueryDepartmentCommand request, CancellationToken cancellationToken)
        {
            int pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
            int pageSize = request.PageSize <= 0 ? 10 : request.PageSize;

            var query = departmentRepository.GetAll()
                .Where(d => d.IsDel == false)
                .WhereIF(!string.IsNullOrWhiteSpace(request.DepartmentName),
                    d => d.DepartmentName.Contains(request.DepartmentName!.Trim()))
                .WhereIF(request.ParentId.HasValue, d => d.ParentId == request.ParentId!.Value)
                .WhereIF(request.Status.HasValue, d => d.Status == request.Status!.Value)
                .OrderBy(d => d.Sort)
                .OrderBy(d => d.Id, OrderByType.Desc)
                .Select(d => new DepartmentDTO
                {
                    Id = d.Id,
                    DepartmentCode = d.DepartmentCode,
                    DepartmentName = d.DepartmentName,
                    ParentId = d.ParentId,
                    Description = d.Description,
                    LeaderId = d.LeaderId,
                    LeaderName = d.LeaderName,
                    Sort = d.Sort,
                    Status = d.Status,
                    Phone = d.Phone,
                    Email = d.Email,
                    Remark = d.Remark,
                    //CreateDate = d.Createdate,
                    //CreateName = d.Createname,
                    //UpdateDate = d.Updatedate,
                    //UpdateName = d.Updatename
                });

            int totalCount = 0;
            var result = query.ToPageList(pageIndex, pageSize, ref totalCount);

            var tree = BuildTree(result, 0);

            return new APIPaging<DepartmentDTO>
            {
                Totalcount = totalCount,
                Code = StateCode.OK,
                Message = "获取部门列表成功",
                ListResult = tree
            };
        }

        /// <summary>
        /// 递归构建部门树
        /// </summary>
        private List<DepartmentDTO> BuildTree(List<DepartmentDTO> allDepts, long parentId)
        {
            var children = allDepts
                .Where(d => d.ParentId == parentId)
                .OrderBy(d => d.Sort)
                .ThenBy(d => d.Id)
                .ToList();

            foreach (var child in children)
            {
                child.Children = BuildTree(allDepts, child.Id);
                child.HasChildren = child.Children.Any();
            }

            return children;
        }
    }
}
